<template>
	<view class="chat_index">
		<mescroll-body ref="mescrollRef" @up="upCallback" @down="downCallback">
			<uni-list>
				<uni-list :border="true">
					<uni-list-chat :clickable="true" @click="$nav('/pages/chat/chat?id='+v.store_id+'&store_name='+v.store.store_name+'&store_logo='+v.store.store_logo)" v-for="(v,k) in list" :key="k" :title="v.store.store_name||'-'" :avatar="v.store.store_logo||'-'" :note="v.chat_msg.content||'-'" :time="formatTime(v.chat_msg.created_at)||'0000-00-00'" badge-positon="left" :badge-text="v.chat_msg.user_read==1?'dot':''"></uni-list-chat>
				</uni-list>
			</uni-list>
		</mescroll-body>
	</view>
</template>
 
<script>
	import moment from "moment";  
	import UniListChat from '@/components/uni-list/uni-list-chat.vue'
	import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
	export default {
		mixins: [MescrollMixin],
		components:{UniListChat},
		data() {
			return {
				params:{
					page:1,
					per_page:10,
				},
				list:[],
				socketObj:null,
				sendMsg:{
				    type:'text', // 类型
				    content:'', // 内容
				    uid:0,
				    send_type:0,
				    store_id:0,
				},
				store_id:0,
				isLogin:false,
				userInfo:undefined,
			};
		},
		onLoad(opt) {
			if(!this.$isEmpty(opt.id)){
				this.store_id = opt.id;
			}
			this.checkLogin();
		},
		onHide() {
			this.socketObj.close({
				complete(e) {
					console.log('关闭socket')
					console.log(e)
				}
			});
		},
		methods:{
			websocketInit(){
				console.log(this.isLogin)
				if(!this.isLogin){
				    return this.$toast('未登陆');
				}
				
				this.socketObj = uni.connectSocket({
					url:this.$api.chatUrl,
					success:()=>{
						console.log("socket连接成功")
					},
					fail:()=>{
						console.log("socket连接失败")
					},
				})
				// 监听socket连接
				this.socketObj.onOpen(()=>{
					this.open();
				})
				
				// 监听socket错误信息
				this.socketObj.onError(()=>{
					 this.error()
				});
				// 监听socket消息
				this.socketObj.onMessage((e)=>{
					this.getMessage(e)
				});
			},
			open() {
			
			    // eslint-disable-next-line no-console
			    console.log("socket连接成功2")
			
			    // 如果登录了，且用户ID存在
			    this.sendMsg.type = 'bind';
			    this.sendMsg.uid = this.userInfo.id;
			    this.sendMsg.store_id = this.store_id;
			    let infoStr = JSON.stringify(this.sendMsg);
				console.log(infoStr)
			    if(this.userInfo.id>0){
			        this.socketObj.send(infoStr); // 发送用户ID到服务器
					
					if(this.store_id !=0){
						this.add_friend(); // 添加商家为好友
					}
			        
			        
			    }
			},
			error() {
			    // eslint-disable-next-line no-console
			    console.log("连接错误")
			},
			getMessage(msg) {
				// console.log(msg);
				
				if(msg == undefined){
				    return;
				}
				
			    let obj = JSON.parse(msg.data);
			
			    if(obj == undefined){
			        return;
			    }
			    // eslint-disable-next-line no-console
			    
			    let chatType = 1;
			    switch(obj.type){
			        case 'bind': // 绑定用户成功
			            break;
			        case 'error':
			            this.$toast('服务端消息接收失败!');
			            break;
			        case 'text': // 文字接收
			            break;
			        case 'image': // 图片接收
			            break;
			        default :  // 都不是
			            chatType = -1;
			            break;
			    }
			
			    if(chatType == -1){
			        return;
			    }
			    console.log(obj)
			    // 只要不是心跳检测，就查询一次好友列表
			    if(obj.type != '@heart@'){
			        this.mescroll.resetUpScroll();
			    }
			
			},
			// send(type) {
			//     this.sendMsg.type = type;
			//     this.sendMsg.store_id = this.store_id;
			//     // 发送信息
				
			// 	let obj = {...this.$api.chats}
			// 	obj.url += '/chat_event'
			// 	obj.method = 'post'
				
			//     this.$http(obj,{data:this.sendMsg}).then(res=>{
			//         if(res.code == 200){
			//             this.$set(this.sendMsg,'content','');
			//             // console.log(this.onChat)
			//             this.scrollDown();
			//         }else{
			//             this.$message.error(res.msg);
			//         }
			//     });
			    
			// },
			close() {
			    // eslint-disable-next-line no-console
			    console.log("socket已经关闭")
			},
			// 把商家添加成好友
			add_friend(){
				let obj = {...this.$api.chats}
				obj.url += '/add_friend'
				obj.method = 'post'
			    this.$http(obj,{store_id:this.store_id}).then(res=>{
			        if(res.code==200){
			            // eslint-disable-next-line no-console
			            console.log(res.msg);
			        }else{
			            console.log(res.msg)
			        }
			    })
			},
			upCallback(page){
				this.params.page = page.num; 
				this.params.per_page = page.size; 
				 
				 let obj = {...this.$api.chats}
				 obj.url += '/friends'
				
				this.$http(obj,this.params).then(res=>{
					if(res.code == 200){
						if(this.params.page == 1){
							this.list = [];
						}
						this.list = this.list.concat(res.data.friends.data||res.data); 
						this.mescroll.endBySize(this.params.per_page, res.data.friends.total); 
						if(res.data.friends.total<8){
							this.mescroll.endUpScroll(false)
						}
						if(res.data.friends.total==0){
							this.mescroll.showEmpty();
						}
					}
				})
			},
			downCallback(){
				this.mescroll.resetUpScroll();
			},
			checkLogin(){
				this.$http(this.$api.checkLogin).then(res=>{
					if(res.code == 200){
						this.isLogin = true;
						this.userInfo = res.data;
						this.websocketInit();
					}else{
						this.isLogin = false;
						this.userInfo = undefined;
					}
				})
			},
			formatTime(e){
				return moment(e).format('yyyy-MM-DD HH:mm:ss');
			}
		}
	}
</script>

<style lang="scss">

</style>
